//
//  CodeHelper.m
//  TVLive
//
//  Created by 肖康龙 on 2017/6/5.
//  Copyright © 2017年 vsoontech. All rights reserved.
//

//#include "KeyModel.h"
#import <UIKit/UIKit.h>
#import "VCInformationTool.h"
#import "VCDeviceInfo.h"

#import "VCCodeHelper.h"

#import "sys/utsname.h"

#import <CommonCrypto/CommonHMAC.h>
#import<CommonCrypto/CommonCryptor.h>
#import "VCDowmload.h"
static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
#define LocalStr_None  @""




@implementation VCCodeHelper
NSString *CodeKeyThree = @"ZAV3141592653510";
NSString *CodeIvThree = @"AHANCKH413566745";

NSString *CodeKeyTwo = @"YZV3141592653589";
NSString *CodeIvTwo = @"PLANCKH413566743";


//Md5
+ (NSString *) md5:(NSString *)str {
    if (str == nil) {
        return nil;
    }
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

//转化为Base64
+ (NSString *)base64StringFromText:(NSString *)text
{
    if (text && ![text isEqualToString:LocalStr_None]) {
        //取项目的bundleIdentifier作为KEY  改动了此处
        //NSString *key = [[NSBundle mainBundle] bundleIdentifier];
        NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
        //IOS 自带DES加密 Begin  改动了此处
        //data = [self DESEncrypt:data WithKey:key];
        //IOS 自带DES加密 End
        return [self base64EncodedStringFrom:data];
    }
    else {
        return LocalStr_None;
    }
}

//由base64转化
+ (NSString *)textFromBase64String:(NSString *)base64
{
    if (base64 && ![base64 isEqualToString:LocalStr_None]) {
        //取项目的bundleIdentifier作为KEY   改动了此处
        //NSString *key = [[NSBundle mainBundle] bundleIdentifier];
        NSData *data = [self dataWithBase64EncodedString:base64];
        //IOS 自带DES解密 Begin    改动了此处
        //data = [self DESDecrypt:data WithKey:key];
        //IOS 自带DES加密 End
        return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    else {
        return LocalStr_None;
    }
}

//DES加密
+(NSString *)encryptSting:(NSString *)sText key:(NSString *)key andDesiv:(NSString *)ivDes
{
    if ((sText == nil || sText.length == 0)
        || (sText == nil || sText.length == 0)
        || (ivDes == nil || ivDes.length == 0)) {
        return @"";
    }
    //gb2312 编码
    NSStringEncoding encoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSData* encryptData = [sText dataUsingEncoding:encoding];
    size_t  dataInLength = [encryptData length];
    const void *   dataIn = (const void *)[encryptData bytes];
    
    CCCryptorStatus ccStatus = 0;
    uint8_t *dataOut = NULL; //可以理解位type/typedef 的缩写（有效的维护了代码，比如：一个人用int，一个人用long。最好用typedef来定义）
    size_t dataOutMoved = 0;
    size_t    dataOutAvailable = (dataInLength + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);  dataOut = malloc( dataOutAvailable * sizeof(uint8_t));
    memset((void *)dataOut, 0x0, dataOutAvailable);//将已开辟内存空间buffer的首 1 个字节的值设为值 0
    const void *iv = (const void *) [ivDes cStringUsingEncoding:NSASCIIStringEncoding];
    //CCCrypt函数 加密/解密
    ccStatus = CCCrypt(kCCEncrypt,//  加密/解密
                       kCCAlgorithmDES,//  加密根据哪个标准（des，3des，aes。。。。）
                       kCCOptionPKCS7Padding,//  选项分组密码算法(des:对每块分组加一次密  3DES：对每块分组加三个不同的密)
                       [key UTF8String],  //密钥    加密和解密的密钥必须一致
                       kCCKeySizeDES,//   DES 密钥的大小（kCCKeySizeDES=8）
                       iv, //  可选的初始矢量
                       dataIn, // 数据的存储单元
                       dataInLength,// 数据的大小
                       (void *)dataOut,// 用于返回数据
                       dataOutAvailable,
                       &dataOutMoved);
    
    //编码 base64
    NSData *data = [NSData dataWithBytes:(const void *)dataOut length:(NSUInteger)dataOutMoved];
    Byte *bytes = (Byte *)[data bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[data length];i++){
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        if([newHexStr length]==1)
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        else
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    free(dataOut);
    return hexStr;
}

//DES解密
+(NSString *)decryptWithDESString:(NSString *)sText key:(NSString *)key andiV:(NSString *)iv
{
    if ((sText == nil || sText.length == 0)
        || (sText == nil || sText.length == 0)
        || (iv == nil || iv.length == 0)) {
        return @"";
    }
    const void *dataIn;
    size_t dataInLength;
    char *myBuffer = (char *)malloc((int)[sText length] / 2 + 1);
    bzero(myBuffer, [sText length] / 2 + 1);
    for (int i = 0; i < [sText length] - 1; i += 2) {
        unsigned int anInt;
        NSString * hexCharStr = [sText substringWithRange:NSMakeRange(i, 2)];
        NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        myBuffer[i / 2] = (char)anInt;
    }
    
    NSData *decryptData =[NSData dataWithBytes:myBuffer length:[sText length] / 2 ];//转成utf-8并decode
    dataInLength = [decryptData length];
    dataIn = [decryptData bytes];
    free(myBuffer);
    CCCryptorStatus ccStatus = 0;
    uint8_t *dataOut = NULL; //可以理解位type/typedef 的缩写（有效的维护了代码，比如：一个人用int，一个人用long。最好用typedef来定义）
    size_t dataOutAvailable = 0; //size_t  是操作符sizeof返回的结果类型
    size_t dataOutMoved = 0;
    
    dataOutAvailable = (dataInLength + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);
    dataOut = malloc( dataOutAvailable * sizeof(uint8_t));
    memset((void *)dataOut, 0x0, dataOutAvailable);//将已开辟内存空间buffer的首 1 个字节的值设为值 0
    
    const void *ivDes = (const void *) [iv cStringUsingEncoding:NSASCIIStringEncoding];
    //CCCrypt函数 加密/解密
    ccStatus = CCCrypt(kCCDecrypt,//  加密/解密
                       kCCAlgorithmDES,//  加密根据哪个标准（des，3des，aes。。。。）
                       kCCOptionPKCS7Padding,//  选项分组密码算法(des:对每块分组加一次密  3DES：对每块分组加三个不同的密)
                       [key UTF8String],  //密钥    加密和解密的密钥必须一致
                       kCCKeySizeDES,//   DES 密钥的大小（kCCKeySizeDES=8）
                       ivDes, //  可选的初始矢量
                       dataIn, // 数据的存储单元
                       dataInLength,// 数据的大小
                       (void *)dataOut,// 用于返回数据
                       dataOutAvailable,
                       &dataOutMoved);
    
    NSStringEncoding encoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    
    NSString *result  = [[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)dataOut length:(NSUInteger)dataOutMoved] encoding:encoding];
    free(dataOut);
    return result;
}

/*反馈boby加密*/
+(NSData *)AESFeedbackWithData:(NSData *)data{
    NSString *string = [self base64EncodedStringFrom:[self AES128EncryptWithKey:CodeKeyTwo iv:CodeIvTwo withNSData:data]];    
    return  [string dataUsingEncoding:NSUTF8StringEncoding];
    
//    return [self AES128EncryptWithKey:CodeKeyTwo iv:CodeIvTwo withNSData:data];
}


+(NSString *)conversionToBase64StringWithData:(NSData *)data{
    
    NSString *string = [self base64EncodedStringFrom:data];
    
//    NSString*encodedString=(NSString*)
//    
//    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)string,NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8));
    return string;
}
//AES加密
+ (NSData *)AES128EncryptWithKey:(NSString *)key iv:(NSString *)iv withNSData:(NSData *)data
{
    char keyPtr[kCCKeySizeAES128+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    char ivPtr[kCCKeySizeAES128+1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          ivPtr,
                                          [data bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    free(buffer);
    return nil;
    
}

//AES解密
+ (NSData *)AES128DecryptWithKey:(NSString *)key iv:(NSString *)iv withNSData:(NSData *)data
{
    
    char keyPtr[kCCKeySizeAES128+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    char ivPtr[kCCKeySizeAES128+1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          ivPtr,
                                          [data bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }
    free(buffer);
    return nil;
    
    
}

/******************************************************************************
 函数名称 : + (NSData *)dataWithBase64EncodedString:(NSString *)string
 函数描述 : base64格式字符串转换为文本数据
 输入参数 : (NSString *)string
 输出参数 : N/A
 返回参数 : (NSData *)
 备注信息 :
 ******************************************************************************/
+ (NSData *)dataWithBase64EncodedString:(NSString *)string
{
    if (string == nil)
        [NSException raise:NSInvalidArgumentException format:nil];
    if ([string length] == 0)
        return [NSData data];
    
    static char *decodingTable = NULL;
    if (decodingTable == NULL)
    {
        decodingTable = malloc(256);
        if (decodingTable == NULL)
            return nil;
        memset(decodingTable, CHAR_MAX, 256);
        NSUInteger i;
        for (i = 0; i < 64; i++)
            decodingTable[(short)encodingTable[i]] = i;
    }
    
    const char *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];
    if (characters == NULL)     //  Not an ASCII string!
        return nil;
    char *bytes = malloc((([string length] + 3) / 4) * 3);
    if (bytes == NULL)
        return nil;
    NSUInteger length = 0;
    
    NSUInteger i = 0;
    while (YES)
    {
        char buffer[4];
        short bufferLength;
        for (bufferLength = 0; bufferLength < 4; i++)
        {
            if (characters[i] == '\0')
                break;
            if (isspace(characters[i]) || characters[i] == '=')
                continue;
            buffer[bufferLength] = decodingTable[(short)characters[i]];
            if (buffer[bufferLength++] == CHAR_MAX)      //  Illegal character!
            {
                free(bytes);
                return nil;
            }
        }
        
        if (bufferLength == 0)
            break;
        if (bufferLength == 1)      //  At least two characters are needed to produce one byte!
        {
            free(bytes);
            return nil;
        }
        
        //  Decode the characters in the buffer to bytes.
        bytes[length++] = (buffer[0] << 2) | (buffer[1] >> 4);
        if (bufferLength > 2)
            bytes[length++] = (buffer[1] << 4) | (buffer[2] >> 2);
        if (bufferLength > 3)
            bytes[length++] = (buffer[2] << 6) | buffer[3];
    }
    
    bytes = realloc(bytes, length);
    return [NSData dataWithBytesNoCopy:bytes length:length];
}

/******************************************************************************
 函数名称 : + (NSString *)base64EncodedStringFrom:(NSData *)data
 函数描述 : 文本数据转换为base64格式字符串
 输入参数 : (NSData *)data
 输出参数 : N/A
 返回参数 : (NSString *)
 备注信息 :
 ******************************************************************************/
+ (NSString *)base64EncodedStringFrom:(NSData *)data
{
    if ([data length] == 0)
        return @"";
    
    char *characters = malloc((([data length] + 2) / 3) * 4);
    if (characters == NULL)
        return nil;
    NSUInteger length = 0;
    
    NSUInteger i = 0;
    while (i < [data length])
    {
        char buffer[3] = {0,0,0};
        short bufferLength = 0;
        while (bufferLength < 3 && i < [data length])
            buffer[bufferLength++] = ((char *)[data bytes])[i++];
        
        //  Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.
        characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];
        characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
        if (bufferLength > 1)
            characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
        else characters[length++] = '=';
        if (bufferLength > 2)
            characters[length++] = encodingTable[buffer[2] & 0x3F];
        else characters[length++] = '=';
    }
    
    return [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];
}

+(NSData *)bas64From:(NSData *)data{
    if ([data length] == 0)
        return nil;
    
    char *characters = malloc((([data length] + 2) / 3) * 4);
    if (characters == NULL)
        return nil;
    NSUInteger length = 0;
    
    NSUInteger i = 0;
    while (i < [data length])
    {
        char buffer[3] = {0,0,0};
        short bufferLength = 0;
        while (bufferLength < 3 && i < [data length])
            buffer[bufferLength++] = ((char *)[data bytes])[i++];
        
        //  Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.
        characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];
        characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
        if (bufferLength > 1)
            characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
        else characters[length++] = '=';
        if (bufferLength > 2)
            characters[length++] = encodingTable[buffer[2] & 0x3F];
        else characters[length++] = '=';
    }
    
    return [NSData dataWithBytes:characters length:length];
}


#pragma mark - 加密
/*i参数加密*/
+(NSString *)AESDecryptIWithType:(int)type isMobileTV:(BOOL)isMobileTV{
    //    buildVersion : 系统版本 model:升级型号  softVersion:软件版本
    NSString *string = [NSString stringWithFormat:@"TwTg{\"buildVersion\":\"%@\",\"channel\":\"\",\"mac\":\"00:00:00:00:00:00\",\"model\":\"%@\",\"sn\":\"\",\"softVersion\":\"%@\",\"uuid\":\"%@\",\"vendorID\":\"\",\"wifiMac\":\"00:00:00:00:00:00\"}",[VCDeviceInfo getSystemVersionString],[VCDeviceInfo deviceVersion],[VCDeviceInfo getCurrentBundleVersion],[VCDeviceInfo getDevicetIdentifier]];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];


    if (type == 2) {
        return [self conversionToBase64StringWithData:[self AES128EncryptWithKey:CodeKeyTwo iv:CodeIvTwo withNSData:data]];
    }
    return [self conversionToBase64StringWithData:[self AES128EncryptWithKey:CodeKeyThree iv:CodeIvThree withNSData:data]];
    
}

/**
 codeId     视频ID
 cnt        返回片段数
 index      从第几片开始，index=0为第一片
 platform   平台
 start      是否是起播
 seekVod    点播seek，毫秒
 seekLive   直播seek，时间戳
 vcurl
 */
+(NSString *)getSoucressListCodeID:(NSString *)codeId
                               cnt:(NSInteger)cnt
                             index:(NSInteger)index
                          platform:(NSString *)platform
                             start:(BOOL)start
                           seekVod:(NSInteger)seekVod
                          seekLive:(NSInteger)seekLive
                             vcurl:(NSString *)vcurl{
//    NSString *string = [NSString stringWithFormat:@"sdse{\"id\":\"%@\"}",codeId];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:codeId forKey:@"id"];
    [dict setObject:@(start) forKey:@"start"];
    [dict setObject:platform forKey:@"platform"];
    [dict setObject:vcurl forKey:@"vcurl"];
    [dict setObject:@(seekVod) forKey:@"seekVod"];
//    if (cnt) [dict setObject:@(cnt) forKey:@"cnt"];
//    if (index) [dict setObject:@(index) forKey:@"index"];
//    if (platform) [dict setObject:platform?platform:@"" forKey:@"platform"];
////    if (seekVod) [dict setObject:@(seekVod) forKey:@"seekVod"];
//    if (seekLive) [dict setObject:@(seekLive) forKey:@"seekLive"];
    
    NSString *string = [NSString stringWithFormat:@"sdse%@",[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]];
        
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    return [self conversionToBase64StringWithData:[self AES128EncryptWithKey:CodeKeyThree iv:CodeIvThree withNSData:data]];
}

/*流量上报
 e.appKey	appkey	 String
 e.resourceID	资源id	String
 e.playTime	播放时长，单位秒	Int
 e.accelSize	加速流量，单位字节	Long
 e.vcSize	Vc总的有效流量	Long
 e.vc		数组
 e.vc.host	Vc节点host	String
 e.vc.tSize	Vc节点总流量，单位字节	Long
 e.vc.vSize	Vc节点有效流量，单位字节	Long
 */
+(NSString *)getReportWithResourceID:(NSString *)resourceID
                            playTime:(NSUInteger)playTime
                           accelSize:(NSUInteger)accelSize
                              vcSize:(NSUInteger)vcSize
                                  vc:(NSArray *)vc{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:APPKEY forKey:@"appKey"];
    [dict setObject:resourceID forKey:@"resourceID"];
    [dict setObject:@(playTime) forKey:@"playTime"];
    [dict setObject:@(accelSize) forKey:@"accelSize"];
    [dict setObject:@(vcSize) forKey:@"vcSize"];
    [dict setObject:vc forKey:@"vc"];
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    
    
    NSString *string = [NSString stringWithFormat:@"hohe%@",[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]];
    
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    return [self conversionToBase64StringWithData:[self AES128EncryptWithKey:CodeKeyThree iv:CodeIvThree withNSData:data]];
}




#pragma mark - 解密
/*解密秘钥*/
+(NSDictionary *)decryptionKeyWithString:(NSData *)data{
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if (string.length<1) {
        return [NSDictionary dictionary];
    }
    NSData *basedata = [self dataWithBase64EncodedString:string];
    [VCInformationTool setKeyDict:[self parsingWithData:basedata Key:CodeKeyThree IV:CodeIvThree]];
    return [VCInformationTool getKeyDict];
    
}
/**解密*/
+(NSDictionary *)decryptionPlayDataWithString:(NSData *)data{
    
    
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if (string.length<1) {
        return [NSDictionary dictionary];
    }
    NSString *subString = [string substringToIndex:4];
    
    
    __block NSString *keyOut;
    __block NSString *ivOut;
    NSDictionary *keyDict = [VCInformationTool getKeyDict];
    [keyDict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        for (NSDictionary *dic in obj) {
            if ([[dic objectForKey:@"a"] isEqualToString:subString]) {
                keyOut = [dic objectForKey:@"b"];
                ivOut = [dic objectForKey:@"c"];
                break;
            }
        }
    }];
    
    
    NSData *basedata = [self dataWithBase64EncodedString:[string substringFromIndex:4]];
    return [self parsingWithData:basedata Key:keyOut IV:ivOut];
    
}


+(NSDictionary *)parsingWithData:(NSData *)basedata Key:(NSString *)key IV:(NSString *)iV{
    
    NSString *decodedString = [[NSString alloc] initWithData:[self AES128DecryptWithKey:key iv:iV withNSData:basedata] encoding:NSUTF8StringEncoding];
    
    
    for (int i = 0; i < decodedString.length; i++) {
        if ([[decodedString substringFromIndex:decodedString.length - i] containsString:@"}"]) {
            decodedString = [decodedString substringToIndex:decodedString.length - i+1];
            break;
        }
        
    }
    NSData *jsonData = [decodedString dataUsingEncoding:NSUTF8StringEncoding];
    if (jsonData) {
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        if (err) {
            return [NSDictionary dictionary];
        }else{
            
            return dic;
        }
    }else{
        return [NSDictionary dictionary];
    }

}

@end
